package com.example.sneakerappforme1105;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.sneakerappforme1105.ViewModel.CartViewModel;
import com.example.sneakerappforme1105.bean.CartItem;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.dao.CartDao;
import com.example.sneakerappforme1105.dao.CartItemDao;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.example.sneakerappforme1105.radiogroup.MyRadioGroup;
import com.example.sneakerappforme1105.util.ToastUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class GoodsDetailActivity extends AppCompatActivity {
    private final String TAG = "detail";
    private TextView tv_title;
    private TextView tv_count;
    private TextView tv_goods_price;
    private TextView tv_goods_desc;
    private ImageView iv_goods_pic;
    private long mGoodsId;  // 来自上一个活动, 用来展示当前的商品
    private long mCartId;  // 通过活动传入, 用来创建和当前商品相关联的 购物车项
    private long mUserId;
    private GoodsDao goodsDao; // 用来查询当前所展示商品的数据
    private CartItemDao cartItemDao; // 用来插入购物车项

    private AlertDialog chooseDialg = null; // 用来弹出窗口码数
    private AlertDialog.Builder builder = null;
    private View view_choose;
    private Goods goods; // 当前展示页的商品, showDetail保存下来
    private List<Float> sizeList;   // 鞋码数
    private float min = 36.5f;
    private List<Double> priceList; // 鞋码对应价格数
    private double price;
    private List<RadioButton> radioButtons;
    private TextView  tv_price; // 选择页的价格
    private TextView tv_size;   // 选择页的尺码
    private MyRadioGroup radioGroup;
    private RadioButton rb2;
    private TextView numberText;
    private String size = "36.5";// 用来记录购买的尺码数
    private CartViewModel cartViewModel;
    private HashMap<Long, Goods> mGoodsMap = new HashMap<>();
    private List<CartItem> mCartItemList = new ArrayList<>();

    // 表格
    private TextView tv_brand;
    private TextView tv_fashou;
    private TextView tv_color;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);

        cartViewModel = MainApplication.getInstance().getCartViewModel();   // 得到 cartViewModel

        cartViewModel.getGoodsMap().observe(this, map -> {
            mGoodsMap = map != null ? map : new HashMap<>();
        }); // 先获得 mGoodsMap
        cartViewModel.getCartItemList().observe(this, items -> {
            mCartItemList = items != null ? items : new ArrayList<>();
        });

        tv_title = findViewById(R.id.tv_title);
        tv_count = findViewById(R.id.tv_count);
        tv_goods_price = findViewById(R.id.tv_goods_price);
        tv_goods_desc = findViewById(R.id.tv_goods_desc);
        iv_goods_pic = findViewById(R.id.iv_goods_pic);

        // 表格
        tv_brand = findViewById(R.id.tv_brand);
        tv_fashou = findViewById(R.id.tv_fashou);
        tv_color = findViewById(R.id.tv_color);

        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(view -> finish());
        ImageView iv_cart= findViewById(R.id.iv_cart);

        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        cartItemDao = MainApplication.getInstance().getAppDatabase().cartItemDao();

        builder = new AlertDialog.Builder(this);
        view_choose = LayoutInflater.from(this).inflate(R.layout.dialogue_choose, null, false);
        builder.setView(view_choose);   // 弹出对话框
        builder.setCancelable(false);
        chooseDialg = builder.create();

        sizeList = getSizeList(min);
        radioGroup = view_choose.findViewById(R.id.radio_size);
        tv_count.setText(""+MainApplication.goodsCount);

        // 11.16 跳转到 购物车片段
        findViewById(R.id.iv_cart).setOnClickListener(view -> {

            Log.d(TAG,"跳转购物车前，有数据"+String.valueOf(mCartItemList.size()));
            Intent intent = new Intent(this,RootActivity.class);
            intent.putExtra("cartId",mCartId);
            intent.putExtra("userId",mUserId);
            intent.putExtra("cartFragment",1);
            startActivity(intent);
        });




        findViewById(R.id.btn_buy).setOnClickListener(view -> {
            chooseDialg.show(); // 展示窗口数据
            if(view_choose!=null){

               ImageView iv_dialogue = view_choose.findViewById(R.id.img_dialogue);
                Glide.with(this)
                        .load(goods.getPicPath()) // 资源 ID
                        .into(iv_dialogue);
               tv_price = view_choose.findViewById(R.id.Text_price);
               tv_price.setText("￥"+String.valueOf(formatDouble(price)));
               tv_size = view_choose.findViewById(R.id.Text_size);
               tv_size.setText("已选尺码 36.5");    // 需要找到被选中的radioGroup

               radioButtons = radioGroup.getAllRadioButtons();
               int idx = 0;

               // 为每个按钮设置价格
               for (RadioButton rd : radioButtons){
                   rd.setText( String.valueOf( formatDouble(sizeList.get(idx)) )+'\n'+"￥"+String.valueOf( formatDouble(priceList.get(idx) )) );
                   rd.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                   idx++;
               }



            numberText = view_choose.findViewById(R.id.textView_chooseNumber);
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                int idx =0;
                for(RadioButton rb: radioButtons){
                    if(rb.getId() == checkedId){

                        if(Integer.parseInt(numberText.getText().toString())!=1) {  // 如果numberText不为1，设置为1
                            numberText.setText("1");
                        }
                        String text = rb.getText().toString();
                        String[] parts = text.split("\n");
                        price = Double.parseDouble(parts[1].substring(1));
                        tv_price.setText("￥"+String.valueOf( formatDouble(price) ));
                        size = parts[0];
                        Log.d(TAG,size);
                        tv_size.setText("已选尺码 "+parts[0]);
                    }
                }

            }});
            }   // view_choose != null
        });

        // 关闭购买窗口
        view_choose.findViewById(R.id.button_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseDialg.dismiss();
                tv_goods_price.setText("￥"+String.valueOf( formatDouble(price) ) );
            }
        });

        view_choose.findViewById(R.id.button_subtract).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                numberText = view_choose.findViewById(R.id.textView_chooseNumber);
                int i = Integer.parseInt(String.valueOf(numberText.getText().toString()));
                if(i>1){
                    i--;
                }
                numberText.setText(String.valueOf(i));
                tv_price.setText("￥"+String.valueOf(formatDouble(i*price)));
            }
        });

        view_choose.findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                numberText = view_choose.findViewById(R.id.textView_chooseNumber);
                int i = Integer.parseInt(String.valueOf(numberText.getText().toString()));
                if(i<goods.getCapcity()){ // 不能超过库存量
                    i++;
                }else{
                    ToastUtil.show(GoodsDetailActivity.this,"已经到达宝贝最大数量~");
                }
                numberText.setText(String.valueOf(i));
                tv_price.setText("￥"+String.valueOf(formatDouble(i*price)));
            }
        });

        view_choose.findViewById(R.id.button_buy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 插入一条 cartItem (goodsId, cartId)
                int num = Integer.parseInt( numberText.getText().toString() );
                if(size!=null){
                    CartItem cartItem = new CartItem(mCartId,mGoodsId,num,price,size,0);    // 先设置为 0
                    if(cartViewModel.addCartItem(cartItem) ){   // 已经存在该商品
                        MainApplication.goodsCount++;   // 新商品
                        tv_count.setText(""+MainApplication.goodsCount);
                        // 插入到 viewmodel中, 加入 mGoodsMap
                        Log.d(TAG,"插入后list的条数为 "+cartViewModel.getCartItemList().getValue().size());
                        Goods goods = goodsDao.queryGoodsByGoodsId(cartItem.getGoodsId());
                        mGoodsMap.put(cartItem.getGoodsId(),goods);
                        cartViewModel.setGoodsMap(mGoodsMap);


                    }
                }

                   // 有数据了, 根据 goodsId把商品信息查询出来
                ToastUtil.show(GoodsDetailActivity.this,"加入购物车成功！^_^");
                chooseDialg.dismiss();
            }
        });



    }// onCreate


    @Override
    protected void onResume() {
        super.onResume();
        showDetail();

    }

    protected void showDetail() {
        mGoodsId = getIntent().getLongExtra("goodsId", 0L);
        mCartId = getIntent().getLongExtra("cartId",0L);    // 到时候要根据cartId构造 cartId项
        mUserId = getIntent().getLongExtra("userId",0L);
        if(mGoodsId > 0) {
            goods = goodsDao.queryGoodsByGoodsId(mGoodsId);
            tv_title.setText(goods.getName());
            tv_goods_desc.setText(goods.getDesc());
            tv_goods_desc.setText(goods.getDesc());
            tv_goods_price.setText("￥"+ (int)goods.getPrice());
            tv_fashou.setText(""+(int)goods.getPrice());
            String description = goods.getDesc(); // 获取描述
            String[] words = description.split(" "); // 按空格分词
            String lastWord = words[words.length - 1]; // 获取最后一个词
            tv_color.setText(lastWord);
            if(goods.getName().contains("New")){
                tv_brand.setText(goods.getName().split(" ")[0]+" "+goods.getName().split(" ")[1]);
            }else{
                tv_brand.setText(goods.getName().split(" ")[0]);
            }


            Glide.get(this).clearMemory();
            Glide.with(this)
                    .load(goods.getPicPath()) // 资源 ID
//                    .skipMemoryCache(true) // 跳过内存缓存
//                    .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                    .into(iv_goods_pic);
        }

        price = goods.getPrice();
        priceList = getPriceList(price); // 初始化价格数组
    }

    private List<Float> getSizeList(float min){
        List<Float> list = new ArrayList<>();
        for(; min<=47.5;min+=0.5){
            list.add(min);
        }

        return list;
    }

    private List<Double> getPriceList(double price){
        List<Double> list = new ArrayList<>();
        for(int i=0;i<sizeList.size();i++){
            double p = price+i*5;
            list.add(p);
        }

        return list;
    }


    public static String formatDouble(double num) {
        // 检查小数部分是否为0
        if (num == (int) num) {
            // 如果小数部分为0，只显示整数部分
            return String.valueOf((int) num);
        } else {
            // 否则显示一位小数
            DecimalFormat df = new DecimalFormat("#.0");
            return df.format(num);
        }
    }


    public void select(View view) {
        int id = view.getId();  // 获取点击的 RadioButton 的 id
        Log.d(TAG, String.valueOf(id));
        System.out.println(id);
        // 使用 radioButtonId 做进一步处理
        // 设置 RadioGroup 按钮监听
        MyRadioGroup radioGroup = view_choose.findViewById(R.id.radio_size);
       radioButtons = radioGroup.getAllRadioButtons();
        if(view_choose!=null) {
            RadioButton rb = view_choose.findViewById(id);
            String text = rb.getText().toString();
            String[] parts = text.split("\n");
            price = Double.parseDouble(parts[1]);
            tv_price.setText("￥"+String.valueOf( formatDouble(price) ));
            tv_size.setText("已选尺码 "+parts[0]);
        }
    }



}